//
//  ByJobVC.m
//  jmsfhz_ios
//
//  Created by pro on 16/7/18.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ByJobVC.h"

/** 单元格 */
#import "ByJobCell.h"                 // 就业单元格

#import "ByJobViewModel.h"            // vm

@interface ByJobVC () <UITableViewDelegate, UITableViewDataSource, ByJobQueryDelegate, ByJobSendDelegate, UISearchBarDelegate>
{
    NSString *_jobID;           // 当选选中的岗位id
    
    NSString *_keywords;                // 搜索内容

}
@property (nonatomic, strong) UITableView *table;

@property (nonatomic, strong) ByJobViewModel *vm;
@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, assign) NSInteger page;

@end

@implementation ByJobVC

- (ByJobViewModel *)vm {
    if (!_vm) {
        _vm = [[ByJobViewModel alloc] init];
        _vm.jobDelegate = self;
        _vm.jobSendDelegate = self;
    }
    return _vm;
}
- (NSMutableArray *)items {
    if (!_items) {
        _items = [[NSMutableArray alloc] init];
    }
    return _items;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"就业";
    
    self.view.backgroundColor = [UIColor whiteColor];

    [self createSearchBar];
    
    [self createTableView];
    
    _page = 1;
    [self.table.mj_header beginRefreshing];
    

}



#pragma mark - Net request
/** 岗位查询 */
- (void)jobQuery {
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    params.page_num = [NSString stringWithFormat:@"%li", _page];
    params.page_size = @"10";
    params.keywords = _keywords;
    [self.vm jobQuery:params];
}
- (void)jobQuerySuccess:(ByNetBaseResult *)result {
    
    ByNetJobModel *model = result.data;
    ARRAR_LOG(model.results);
    /** 数据数组赋值，并刷新table，取消hud */

    if (_page == 1) {
        [self.items removeAllObjects];
        [self.items addObjectsFromArray:model.results];
        [self.table.mj_footer resetNoMoreData];
    } else {
        [self.items addObjectsFromArray:model.results];
    }
    
    [self.table reloadData];
    if (self.items.count == model.total.integerValue) {
        [self.table.mj_header endRefreshing];
        [self.table.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    [self.table.mj_footer endRefreshing];
    [self.table.mj_header endRefreshing];
}
- (void)jobQueryFailure:(ByNetBaseResult *)result {
    [self.table.mj_footer endRefreshing];
    [self.table.mj_header endRefreshing];
    [ByCoreToolAlert alertError:result.msg];
}
/** 投简历 */
- (void)jobSend {
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    params.id = _jobID;
    params.uid = BY_USER.uid;
    [self.vm jobSend:params];
}
- (void)jobSendSuccess:(ByNetBaseResult *)result {
    NSLog(@"%@", result.data);
}
- (void)jobSendFailure:(ByNetBaseResult *)result {
    [ByCoreToolAlert alertError:result.msg];
}

#pragma mark - create view
- (void)createSearchBar {
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.8, 30)];
    
    titleView.layer.cornerRadius = 15;
    titleView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    imageView.y = titleView.height / 2;
    imageView.x = titleView.height / 2;
    imageView.image = [UIImage imageNamed:@"sousuo"];
    [titleView addSubview:imageView];
    
    UITextField *searchBar = [[UITextField alloc] initWithFrame:CGRectMake(imageView.right + 5, 0, titleView.width - imageView.right - 15, titleView.height)];
    searchBar.clearButtonMode = UITextFieldViewModeWhileEditing;
    searchBar.clearsOnBeginEditing = YES;
    searchBar.returnKeyType = UIReturnKeySearch;
    searchBar.placeholder = @"搜索职位";
    searchBar.textColor = [UIColor whiteColor];
    searchBar.font = FONT(14);
    [searchBar addTarget:self action:@selector(search:) forControlEvents:UIControlEventEditingDidEndOnExit];

    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:searchBar.placeholder];
    [attr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, attr.length)];
    searchBar.attributedPlaceholder = attr;
    [titleView addSubview:searchBar];
    
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = titleView;

}
- (void)createTableView {
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    
    ByCoreRefreshGifFooter *footer = [ByCoreRefreshGifFooter footerWithRefreshingBlock:^{
        _page ++;
        [self jobQuery];
    }];
    ByCoreRefreshGifHeader *header = [ByCoreRefreshGifHeader headerWithRefreshingBlock:^{
        _page = 1;
        [self jobQuery];
    }];
    self.table.mj_footer = footer;
    self.table.mj_header = header;
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.items.count;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ByJobCell *cell = [ByJobCell createCellInTableview:tableView];
    cell.model = self.items[indexPath.section];
    return cell;
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.5;
    } else {
        return 5;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    ByNetJobItemModel *model = self.items[indexPath.section];
    NSString *jobID = model.id;
    _jobID = jobID; 
    NSString *urlStr = [NSString stringWithFormat:@"Webview/Company/detail?id=%@", jobID];
    ByWebViewController *vc = [[ByWebViewController alloc] initWithUrlString:urlStr];
    vc.navigationItem.title = @"职位详情";
    
    /** 如果用户已登录，且登录角色为学生，才显示投简历的按钮 */
    if (BY_USER && BY_USER.user_roles.integerValue == BY_USER_ROLE_STUDENT) {
        UIView *basalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
        basalView.backgroundColor = [UIColor whiteColor];
        [BoyeViewHandle createButtonInView:basalView config:^(UIButton *button) {
            button.frame = CGRectMake(20, 10, basalView.width - 20 * 2, 35);
            button.backgroundColor = JM_THEME_COLOR;
            [button setTitle:@"投简历" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            button.titleLabel.font = FONT(16);
            button.layer.cornerRadius = 5;
            [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
        }];
        [vc.view addSubview:basalView];
        basalView.bottom = SCREEN_HEIGHT - 64;
        vc.webView.height -= basalView.height;
        vc.webView.scrollView.backgroundColor = [UIColor whiteColor];       // 使bounces时背景显示白色
    }
   
    [self.navigationController pushViewController:vc animated:YES];

}


#pragma mark - 点击事件
- (void)buttonAction {

    if (!BY_USER) { // 未登陆，则先去登陆
        ByLoginVC *vc = [[ByLoginVC alloc] init];
        ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
        [self presentViewController:navi animated:YES completion:nil];
        return;
    }
    
    [self jobSend]; // 投简历

}
- (void)search:(UITextField *)tf {
    
    if (tf.text.length == 0) {
        _keywords = nil;
    } else {
        _keywords = tf.text;
    }
    
    [self.table.mj_header beginRefreshing];
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    NSLog(@"%@ memory warning", [self class]);
    
    if ([self.view window] == nil)// 是否是正在使用的视图
        
    {
        
        // Add code to preserve data stored in the views that might be
        
        // needed later.
        
        
        
        // Add code to clean up other strong references to the view in
        
        // the view hierarchy.
        
        self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        
    }

}



@end
